﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>盘点订单管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
        }

        #tableBlock {
            margin: 20px auto;
            width: 100%;
            max-width: max-content;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            border-radius: 6px;
        }

        .search-area {
            padding: 20px;
            border-bottom: 0px solid #ebeef5;
        }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding: 20px;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
            display: flex;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            padding: 0 20px;
        }

        .operate-btn {
            margin-right: 8px;
        }

        .btnAndTable {
            margin: 0 auto;
            padding: 0 20px;
        }

        .search-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 15px;
        }

        .search-item {
            display: flex;
            align-items: center;
        }

            .search-item label {
                min-width: 80px;
                text-align: right;
                margin-right: 10px;
            }

        .status-tag {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-draft {
            background-color: #f0f0f0;
            color: #666;
        }

        .status-pending {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-rejected {
            background-color: #fff2f0;
            color: #ff4d4f;
        }

        .status-approved {
            background-color: #f6ffed;
            color: #52c41a;
        }

        .status-closed {
            background-color: #f5f5f5;
            color: #8c8c8c;
        }

        .status-invalid {
            background-color: #fff1f0;
            color: #d9182e;
        }

        .status-inbound {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-outbound {
            background-color: #f6ffed;
            color: #52c41a;
        }

        .status-none {
            background-color: #f5f5f5;
            color: #8c8c8c;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout" style="max-width: max-content;">
        <div id="tableBlock">
            <!-- 查询区域 -->
            <div class="search-area">
                <div class="search-row">
                    <div class="search-item">
                        <label>盘点单号：</label>
                        <el-input type="text" v-model="searchForm.inventoryOrderNo" class="formTableInput" placeholder="请输入盘点单号"></el-input>
                    </div>
                    <div class="search-item">
                        <label>盘点结果：</label>
                        <el-select v-model="searchForm.inventoryResult" class="formTableSelect" placeholder="请选择盘点结果">
                            <el-option label="全部" value=""></el-option>
                            <!-- 从数据字典动态生成选项 -->
                            <el-option v-for="item in inventoryResultOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>仓库名称：</label>
                        <el-select v-model="searchForm.warehouseId" class="formTableSelect" placeholder="请选择仓库名称">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="item in warehouseOptions"
                                       :key="item.id"
                                       :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>盘点类型：</label>
                        <el-select v-model="searchForm.inventoryType" class="formTableSelect" placeholder="请选择盘点类型">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="item in inventoryTypeOptions"
                                       :key="item.code"
                                       :label="item.name"
                                       :value="item.code"></el-option>
                        </el-select>
                    </div>
                    <el-button type="default" v-on:click="resetForm">重置</el-button>
                    <el-button type="primary" v-on:click="searchTable">查询</el-button>
                    <el-button type="default">高级搜索</el-button>
                </div>
                <div class="buttonBlock">
                    <el-button type="primary" v-on:click="addStockTake">新增</el-button>
                    <el-button type="default" v-on:click="deleteStockTake">删除</el-button>
                    <el-button type="default" v-on:click="invalidStockTake">作废</el-button>
                    <el-button type="success" v-on:click="batchAudit">审核</el-button>
                    <el-button type="warning" v-on:click="batchRejectCancel">撤销</el-button>
                    <el-button type="default" v-on:click="lockWarehouse">锁定仓库</el-button>
                    <el-button type="default" v-on:click="exportTable">导出</el-button>
                    <el-button type="success" v-on:click="refreshTable">刷新</el-button>
                </div>
            </div>

            <!-- 表格区域 -->
            <div class="btnAndTable">
                <el-table :data="paginatedData"
                          style="width: 100%; margin-top: 10px"
                          v-on:selection-change="handleSelectionChange"
                          ref="multipleTable"
                          stripe
                          border>
                    <!-- 表格列定义保持不变 -->
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed prop="inventory_order_no" label="盘点单号" width="150">
                        <template #default="scope">
                            <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">
                                {{ scope.row.inventory_order_no }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="inventoryResult" label="盘点结果" width="120">
                        <template #default="scope">
                            <span :class="['status-tag', getResultClass(scope.row.inventoryResult)]">
                                {{ scope.row.inventoryResult }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="warehouse_name" label="仓库名称" width="120"></el-table-column>
                    <el-table-column prop="inventory_type" label="盘点类型" width="120">
                        <template #default="scope">
                            {{ getInventoryTypeText(scope.row.inventory_type) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="inventory_start_time" label="盘点开始时间" width="160">
                        <template #default="scope">{{ formatDateTime(scope.row.inventory_start_time) }}</template>
                    </el-table-column>
                    <el-table-column prop="inventory_end_time" label="盘点结束时间" width="160">
                        <template #default="scope">{{ formatDateTime(scope.row.inventory_end_time) }}</template>
                    </el-table-column>
                    <el-table-column prop="outbound" label="出库状态" width="120">
                        <template #default="scope">
                            <span :class="['status-tag', getOutStatusClass(scope.row.outbound)]">
                                {{ getOutboundText(scope.row.outbound) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="inbound" label="入库状态" width="120">
                        <template #default="scope">
                            <span :class="['status-tag', getInboundStatusClass(scope.row.inbound)]">
                                {{ getInboundText(scope.row.inbound) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="goods_names" label="盘点货品" width="200">
                        <template #default="scope">{{ scope.row.goods_names || '无' }}</template>
                    </el-table-column>
                    <el-table-column prop="inventory_quantity" label="盘点数量" width="120">
                        <template #default="scope">{{ formatNumber(scope.row.inventory_quantity) }}</template>
                    </el-table-column>
                    <el-table-column prop="total_profit_quantity" label="盘盈数量" width="120">
                        <template #default="scope">
                            <span style="color: #52c41a;">{{ formatNumber(scope.row.total_profit_quantity) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_loss_quantity" label="盘亏数量" width="120">
                        <template #default="scope">
                            <span style="color: #ff4d4f;">{{ formatNumber(scope.row.total_loss_quantity) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_profit_amount" label="盘盈金额" width="120">
                        <template #default="scope">
                            <span style="color: #52c41a;">¥{{ formatCurrency(scope.row.total_profit_amount) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_loss_amount" label="盘亏金额" width="120">
                        <template #default="scope">
                            <span style="color: #ff4d4f;">-¥{{ formatCurrency(scope.row.total_loss_amount) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="create_by" label="经办人" width="120"></el-table-column>
                    <el-table-column prop="auditor_by" label="制单人" width="120"></el-table-column>
                    <el-table-column prop="create_org_name" label="所在部门" width="120"></el-table-column>
                    <el-table-column prop="create_time" label="制单时间" width="160">
                        <template #default="scope">{{ formatDateTime(scope.row.create_time) }}</template>
                    </el-table-column>

                    <!-- 操作列 -->
                    <el-table-column fixed="right" label="操作" min-width="180">
                        <template #default="scope">
                            <!-- 1. 草稿(0)/待审核(1)状态：显示【删除】【作废】 -->
                            <el-button v-if="scope.row.order_status === '0' || scope.row.order_status === '1'"
                                       class="operate-btn"
                                       link type="danger" size="default"
                                       v-on:click="deleteSingleStockTake(scope.row)">
                                删除
                            </el-button>

                            <el-button v-if="scope.row.order_status === '0' || scope.row.order_status === '1'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="invalidSingleStockTake(scope.row)">
                                作废
                            </el-button>

                            <!-- 2. 已驳回(2)状态：显示【撤销】【作废】 -->
                            <el-button v-if="scope.row.order_status === '2'"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="handleRejectCancel(scope.row)">
                                撤销
                            </el-button>
                            <el-button v-if="scope.row.order_status === '2'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="invalidSingleStockTake(scope.row)">
                                作废
                            </el-button>

                            <!-- 3. 已审核(3)状态：显示【关闭】【作废】（有入库出库则无撤销） -->
                            <el-button v-if="scope.row.order_status === '3' && !scope.row.hasInOutRecord"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="undoAudit(scope.row)">
                                撤销审核
                            </el-button>
                            <el-button v-if="scope.row.order_status === '3'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="closeStockTake(scope.row)">
                                关闭
                            </el-button>
                            <el-button v-if="scope.row.order_status === '3'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="invalidSingleStockTake(scope.row)">
                                作废
                            </el-button>

                            <!-- 4. 已关闭(4)状态：显示【启用】【作废】（有入库出库则无撤销） -->
                            <el-button v-if="scope.row.order_status === '4' && !scope.row.hasInOutRecord"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="undoClose(scope.row)">
                                撤销关闭
                            </el-button>
                            <el-button v-if="scope.row.order_status === '4'"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="enableStockTake(scope.row)">
                                启用
                            </el-button>
                            <el-button v-if="scope.row.order_status === '4'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="invalidSingleStockTake(scope.row)">
                                作废
                            </el-button>

                            <!-- 5. 已作废(5)状态：显示【撤销作废】（有入库出库则无） -->
                            <el-button v-if="scope.row.order_status === '5' && !scope.row.hasInOutRecord"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="undoInvalidStockTake(scope.row)">
                                撤销作废
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage"
                               v-model:page-size="pageSize"
                               :page-sizes="[10, 20, 50, 100]"
                               :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handleSizeChange"
                               v-on:current-change="handleCurrentChange"></el-pagination>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, computed } = Vue;
        const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;

        // 状态映射配置
        const STATUS_CONFIG = {
            '0': { text: '草稿', class: 'status-draft' },
            '1': { text: '待审核', class: 'status-pending' },
            '2': { text: '已驳回', class: 'status-rejected' },
            '3': { text: '已审核', class: 'status-approved' },
            '4': { text: '已关闭', class: 'status-closed' },
            '5': { text: '已作废', class: 'status-invalid' }
        };

        // 入库/出库编码映射配置
        const INBOUND_CODE_CONFIG = {
            '0': '未入库',
            '1': '已入库',
            '2': '部分入库'
        };
        const OUTBOUND_CODE_CONFIG = {
            '0': '未出库',
            '1': '已出库',
            '2': '部分出库'
        };

        // 入库/出库状态样式配置
        const INBOUND_STATUS_CONFIG = {
            '未入库': { class: 'status-none' },
            '部分入库': { class: 'status-pending' },
            '已入库': { class: 'status-inbound' }
        };
        const OUTBOUND_STATUS_CONFIG = {
            '未出库': { class: 'status-none' },
            '部分出库': { class: 'status-pending' },
            '已出库': { class: 'status-outbound' }
        };

        const RESULT_CONFIG = {
            '有盈亏': { class: 'status-rejected' },
            '无盈亏': { class: 'status-approved' }
        };

        // 状态文本获取方法
        const getInboundText = (code) => INBOUND_CODE_CONFIG[code] || code;
        const getOutboundText = (code) => OUTBOUND_CODE_CONFIG[code] || code;
        const getInboundStatusClass = (code) => {
            const text = getInboundText(code);
            return INBOUND_STATUS_CONFIG[text]?.class || 'status-none';
        };
        const getOutStatusClass = (code) => {
            const text = getOutboundText(code);
            return OUTBOUND_STATUS_CONFIG[text]?.class || 'status-none';
        };
        const getResultClass = (result) => RESULT_CONFIG[result]?.class || 'status-none';

        const app = createApp({
            setup() {
                // 1. 基础数据初始化
                const searchForm = ref({
                    inventoryOrderNo: '',
                    inventoryResult: '',
                    inventoryType: '',
                    warehouseId: ''
                });

                const allTableData = ref([]);
                const filteredData = ref([]);
                const selectedRows = ref([]);
                const multipleTable = ref(null);

                // 2. 分页逻辑
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = computed(() => allTableData.value.length);
                const paginatedData = computed(() => {
                    const start = (currentPage.value - 1) * pageSize.value;
                    const end = start + pageSize.value;
                    return allTableData.value.slice(start, end);
                });

                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                };

                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    multipleTable.value?.clearSelection();
                    selectedRows.value = [];
                };

                // 表格选中事件
                const handleSelectionChange = (selection) => {
                    selectedRows.value = selection;
                };

                // 3. 状态转换辅助方法
                const getStatusText = (status) => STATUS_CONFIG[status]?.text || '未知状态';
                const getInventoryTypeText = (typeCode) => {
                    const type = inventoryTypeOptions.value.find(item => item.code === typeCode);
                    return type ? type.name : typeCode;
                };

                const inventoryResultOptions = ref([]);
                const inventoryTypeOptions = ref([]);
                const warehouseOptions = ref([]);

                // 4. 数据字典和仓库列表加载
                const loadDictData = async () => {
                    try {
                        const typeRes = await axios.get('/WhStockTake/GetInventoryTypes');
                        if (typeRes.data.code === 200) {
                            inventoryTypeOptions.value = typeRes.data.data;
                        }

                        const resultRes = await axios.get('/WhStockTake/GetDictDataList?dictTypeId=13');
                        if (resultRes.data.code === 200) {
                            const filtered = resultRes.data.data.filter(item =>
                                item.name === '有盈亏' || item.name === '无盈亏'
                            );
                            inventoryResultOptions.value = filtered.map(item => ({
                                label: item.name,
                                value: item.code
                            }));
                        }

                        const warehouseRes = await axios.get('/WhStockTake/GetWarehouseList');
                        if (warehouseRes.data.code === 200) {
                            warehouseOptions.value = warehouseRes.data.data;
                        }
                    } catch (error) {
                        console.error('加载字典数据失败:', error);
                        ElMessage.error('加载字典数据失败，请重试');
                    }
                };

                // 5. 搜索功能
                const searchTable = () => {
                    const filtered = allTableData.value.filter(row => {
                        const matchOrderNo = !searchForm.value.inventoryOrderNo ||
                            row.inventory_order_no.includes(searchForm.value.inventoryOrderNo);
                        // 调整为文字匹配（假设后端返回的是“有盈亏”“无盈亏”）
                        const matchResult = !searchForm.value.inventoryResult ||
                            row.inventoryResult === (searchForm.value.inventoryResult === '1' ? '有盈亏' : '无盈亏');
                        const matchType = !searchForm.value.inventoryType ||
                            row.inventory_type === searchForm.value.inventoryType;
                        const matchWarehouse = !searchForm.value.warehouseId ||
                            row.warehouse_id == searchForm.value.warehouseId;
                        return matchOrderNo && matchResult && matchType && matchWarehouse;
                    });
                    allTableData.value = filtered;
                    currentPage.value = 1;
                    ElMessage.success(`查询到 ${filtered.length} 条数据！`);
                };

                const resetForm = () => {
                    searchForm.value = {
                        inventoryOrderNo: '',
                        inventoryResult: '',
                        inventoryType: '',
                        warehouseId: ''
                    };
                    refreshTable();
                };

                // 6. 表格数据刷新 & 盘点结果自动计算
                const refreshData = async () => {
                    try {
                        console.log("开始请求盘点单聚合数据...");
                        const response = await axios.post('/WhStockTake/GetInventoryAggregateList');
                        console.log("API响应:", response);

                        if (response.data.code === 200) {
                            console.log("API返回数据:", response.data.data);
                            let data = response.data.data;

                            if (!data || data.length === 0) {
                                console.log("API返回空数据");
                                ElMessage.warning('暂无盘点单数据');
                                allTableData.value = [];
                                return;
                            }

                            // 自动计算盘点结果：有盘盈或盘亏则为“有盈亏”，否则为“无盈亏”
                            data = data.map(item => ({
                                ...item,
                                inventoryResult: (item.total_profit_quantity > 0 || item.total_loss_quantity > 0)
                                    ? '有盈亏'
                                    : '无盈亏',
                                warehouseName: item.warehouseName || '未知仓库',
                                inventoryType: item.inventoryType || '',
                                create_by: item.create_by || '未知经办人',
                                auditor_by: item.auditor_by || '未知制单人',
                                create_org_name: item.create_org_name || '未知部门',
                                goods_names: item.goods_names || '无',
                                inventory_quantity: item.inventory_quantity || 0,
                                total_profit_quantity: item.total_profit_quantity || 0,
                                total_loss_quantity: item.total_loss_quantity || 0,
                                total_profit_amount: item.total_profit_amount || 0,
                                total_loss_amount: item.total_loss_amount || 0,
                                inbound: item.inbound || '0',
                                outbound: item.outbound || '0',
                                hasInOutRecord: false
                            }));

                            allTableData.value = data;
                            console.log("最终表格数据:", allTableData.value);
                            ElMessage.success(`成功加载 ${data.length} 条盘点单数据`);
                        } else {
                            console.error("API返回错误:", response.data.msg);
                            ElMessage.error(`数据加载失败: ${response.data.msg}`);
                        }
                    } catch (error) {
                        console.error('加载出错:', error);
                        ElMessage.error('数据加载失败，请重试');
                    }
                };

                const refreshTable = async () => {
                    multipleTable.value?.clearSelection();
                    selectedRows.value = [];
                    currentPage.value = 1;
                    await refreshData();
                };

                // 7. 辅助方法：金额格式化（去掉美元符，保留两位小数）
                const formatCurrency = (amount) => {
                    if (!amount) return '0.00';
                    return Number(amount).toFixed(2);
                };

                const formatNumber = (num) => {
                    if (!num) return '0';
                    return Number(num).toLocaleString();
                };

                const formatDateTime = (date) => {
                    if (!date) return '';
                    const dt = new Date(date);
                    return `${dt.getFullYear()}-${(dt.getMonth() + 1).toString().padStart(2, '0')}-${dt.getDate().toString().padStart(2, '0')} ${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}`;
                };

                // 8. 表格操作方法实现
                const jumpToDetail = (row) => {
                    ElMessage.info(`跳转至盘点单${row.inventory_order_no}的详情页`);
                    window.location.href = `/WhStockTake/Details?id=${row.inventory_order_id}`;
                };

                const exportTable = () => {
                    ElMessage.success('导出请求已触发，正在下载...');
                };

                const addStockTake = () => {
                    ElNotification({ title: '提示', message: '跳转至新增盘点单页面', type: 'info' });
                    window.location.href = '/WhStockTake/Create';
                };

                // 批量删除
                const deleteStockTake = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选择要删除的盘点单');
                        return;
                    }
                    ElMessageBox.confirm('确定要删除选中的盘点单吗？', '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('删除成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                };

                // 单个删除
                const deleteSingleStockTake = (row) => {
                    ElMessageBox.confirm(`确定要删除盘点单 ${row.inventory_order_no} 吗？`, '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('删除成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                };

                // 批量作废
                const invalidStockTake = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选择要作废的盘点单');
                        return;
                    }
                    ElMessageBox.confirm('确定要作废选中的盘点单吗？', '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('作废成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消作废');
                    });
                };

                // 单个作废
                const invalidSingleStockTake = (row) => {
                    ElMessageBox.confirm(`确定要作废盘点单 ${row.inventory_order_no} 吗？`, '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('作废成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消作废');
                    });
                };

                // 批量审核
                // 批量审核 - 修复版本
                const batchAudit = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选择要审核的盘点单');
                        return;
                    }

                    // 检查选中的盘点单是否都是可审核状态
                    const validRows = selectedRows.value.filter(row =>
                        row.order_status === '0' || row.order_status === '1'
                    );

                    if (validRows.length === 0) {
                        ElMessage.warning('选中的盘点单中没有可审核的盘点单（只能审核草稿或待审核状态的盘点单）');
                        return;
                    }

                    ElMessageBox.confirm(
                        `确定要审核选中的 ${validRows.length} 条盘点单吗？审核通过后将自动调整库存（盘盈入库、盘亏出库）`,
                        '批量审核确认', {
                        confirmButtonText: '确定审核',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            let successCount = 0;
                            let failCount = 0;
                            const failMessages = [];

                            for (const row of validRows) {
                                console.log('正在审核盘点单:', {
                                    id: row.inventory_order_id,
                                    no: row.inventory_order_no,
                                    status: row.order_status
                                });

                                try {
                                    // 注意：这里使用 GET 参数而不是 POST body
                                    const response = await axios.post(`/WhStockTake/UpdateStatus?id=${row.inventory_order_id}&status=3&auditorComment=批量审核通过`);

                                    console.log('审核API响应:', response.data);

                                    if (response.data.code === 200) {
                                        successCount++;
                                        console.log(`盘点单 ${row.inventory_order_no} 审核成功`);
                                    } else {
                                        failCount++;
                                        failMessages.push(`${row.inventory_order_no}: ${response.data.msg}`);
                                        console.error(`审核失败 ${row.inventory_order_no}:`, response.data.msg);
                                    }
                                } catch (error) {
                                    failCount++;
                                    const errorMsg = error.response?.data?.msg || error.message;
                                    failMessages.push(`${row.inventory_order_no}: ${errorMsg}`);
                                    console.error(`审核异常 ${row.inventory_order_no}:`, error);
                                }
                            }

                            let message = '';
                            if (successCount > 0) {
                                message += `审核成功 ${successCount} 条数据，库存已自动调整`;
                            }
                            if (failCount > 0) {
                                message += ` ${failCount} 条数据审核失败`;
                                if (failMessages.length > 0) {
                                    console.log('失败详情:', failMessages);
                                }
                            }

                            if (successCount > 0) {
                                ElMessage.success(message);
                                await refreshTable();
                            } else {
                                ElMessage.error(message || '全部审核失败');
                            }

                        } catch (error) {
                            console.error('批量审核整体失败:', error);
                            ElMessage.error('批量审核失败，请重试');
                        }
                    }).catch(() => {
                        ElMessage.info('已取消批量审核');
                    });
                };

                // 批量撤销
                const batchRejectCancel = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选择要撤销的盘点单');
                        return;
                    }
                    ElMessageBox.confirm('确定要撤销选中的盘点单吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        ElMessage.success('撤销成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消撤销');
                    });
                };

                // 锁定仓库
                const lockWarehouse = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选择要锁定仓库的盘点单');
                        return;
                    }
                    ElMessageBox.confirm('确定要锁定选中盘点单的仓库吗？', '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('仓库锁定成功');
                    }).catch(() => {
                        ElMessage.info('已取消锁定');
                    });
                };

                // 处理驳回撤销
                const handleRejectCancel = (row) => {
                    ElMessageBox.confirm(`确定要撤销盘点单 ${row.inventory_order_no} 的驳回状态吗？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        ElMessage.success('撤销成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消撤销');
                    });
                };

                // 关闭盘点单
                const closeStockTake = (row) => {
                    ElMessageBox.confirm(`确定要关闭盘点单 ${row.inventory_order_no} 吗？`, '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        ElMessage.success('关闭成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消关闭');
                    });
                };

                // 启用盘点单
                const enableStockTake = (row) => {
                    ElMessageBox.confirm(`确定要启用盘点单 ${row.inventory_order_no} 吗？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        ElMessage.success('启用成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消启用');
                    });
                };

                // 撤销审核
                const undoAudit = (row) => {
                    ElMessageBox.confirm(`确定要撤销盘点单 ${row.inventory_order_no} 的审核状态吗？将同时回滚库存调整记录`, '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const response = await axios.post(`/WhStockTake/UpdateStatus`, {
                                id: row.inventory_order_id,
                                status: '1', // 回滚为待审核状态
                                auditorComment: '撤销审核'
                            });
                            if (response.data.code === 200) {
                                ElMessage.success(`盘点单 ${row.inventory_order_no} 撤销审核成功，库存已回滚`);
                                await refreshTable();
                            } else {
                                ElMessage.error(`撤销失败：${response.data.msg}`);
                            }
                        } catch (error) {
                            console.error('撤销审核失败:', error);
                            ElMessage.error('撤销失败，请重试');
                        }
                    }).catch(() => {
                        ElMessage.info('已取消撤销审核');
                    });
                };

                // 撤销关闭
                const undoClose = (row) => {
                    ElMessageBox.confirm(`确定要撤销盘点单 ${row.inventory_order_no} 的关闭状态吗？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        ElMessage.success('撤销关闭成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消撤销关闭');
                    });
                };

                // 撤销作废
                const undoInvalidStockTake = (row) => {
                    ElMessageBox.confirm(`确定要撤销盘点单 ${row.inventory_order_no} 的作废状态吗？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        ElMessage.success('撤销作废成功');
                        refreshTable();
                    }).catch(() => {
                        ElMessage.info('已取消撤销作废');
                    });
                };

                // 9. 初始化加载数据
                onMounted(async () => {
                    await loadDictData();
                    await refreshData();
                });

                // 暴露所有需要的方法和数据
                return {
                    searchForm,
                    allTableData,
                    paginatedData,
                    selectedRows,
                    multipleTable,
                    currentPage,
                    pageSize,
                    total,
                    inventoryResultOptions,
                    inventoryTypeOptions,
                    warehouseOptions,
                    handleSizeChange,
                    handleCurrentChange,
                    handleSelectionChange,
                    getStatusText,
                    getInboundStatusClass,
                    getOutStatusClass,
                    getInboundText,
                    getOutboundText,
                    getResultClass,
                    getInventoryTypeText,
                    deleteSingleStockTake,
                    handleRejectCancel,
                    closeStockTake,
                    enableStockTake,
                    deleteStockTake,
                    invalidSingleStockTake,
                    invalidStockTake,
                    lockWarehouse,
                    formatDateTime,
                    formatNumber,
                    formatCurrency,
                    jumpToDetail,
                    exportTable,
                    refreshTable,
                    resetForm,
                    searchTable,
                    addStockTake,
                    batchAudit,
                    batchRejectCancel,
                    undoAudit,
                    undoClose,
                    undoInvalidStockTake
                };
            }
        });
        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>